######################################################################################
#
# This file was provided as part of the SharePoint Mystery Deployment package
# Created by Christopher Kimbell (http://sharepointmystery.com)
#
######################################################################################

# -----------------------------------------------------------------
# Creates an object used to manipulate the State Service
# -----------------------------------------------------------------
function New-StateService()
{
    $obj=new-object PSObject -Property @{
      Name = "State Service";
      Proxy = "State Service Proxy";
      DB = New-Database;
      DefaultProxyGroup = $true;
    }
    
    # -----------------------------------------------------------------
    # Validates the information in the object
    # -----------------------------------------------------------------
    Add-Method $obj "Validate" `
    {
        Write-Operation "Validating State Service Service"
        $this.DB.Validate()
        Validate-NotEmpty "Name" $this.Name
        Validate-NotEmpty "Proxy" $this.Proxy  
    }
    # -----------------------------------------------------------------
    # Provisions the Service
    # -----------------------------------------------------------------
    Add-Method $obj "Provision" `
    {
        $sa = Get-SPServiceApplication  | Where-Object {$_.DisplayName -eq $this.Name}

        if($sa -eq $null)
        {
            Write-Operation "Creating $($this.Name)"
                        
            $sa = New-SPStateServiceApplication -Name $this.Name 
            # database is automatically created, gives error if we pre-create it
            New-SPStateServiceDatabase -Name $this.DB.FullName -ServiceApplication  $sa
        }
        else
        {
            Write-OperationDone "$($this.Name) has already been provisioned"  
        } 
         
        $proxy = Get-SPServiceApplicationProxy  | Where-Object {$_.DisplayName -eq $this.Proxy}  
        if($proxy -eq $null)
        {
            New-SPStateServiceApplicationProxy -ServiceApplication $sa `
                -Name $this.Proxy `
                -DefaultProxyGroup:$this.DefaultProxyGroup
        }
        else
        {
            Write-OperationDone "$($this.Proxy) has already been provisioned"  
        }
        return $sa
    }
    # -----------------------------------------------------------------
    # Unprovisions the Service
    # -----------------------------------------------------------------
    Add-Method $obj "Unprovision" `
    {
        Remove-ServiceApplicationProxy $this.Proxy
        Remove-ServiceApplication $this.Name
    }
    return $obj
}
